package edu.hrbeu;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author wzq
 * @create 2022-01-07-16:16
 */
@Component
public class ZuulTokenFilter extends ZuulFilter {

    @Override
    public String filterType() {//声明过滤类型
        return "pre";
    }

    @Override
    public int filterOrder() {//定义过滤器执行顺序
        return 0;
    }

    @Override
    public boolean shouldFilter() {//过滤器是否工作
        return true;
    }

    @Override
    public Object run() throws ZuulException {
//        获取其请求对象中的token参数
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        String token = request.getParameter("token");
//        对token进行非空判断
        if (token == null || !token.startsWith("hrbeu-")) {
            HttpServletResponse response = requestContext.getResponse();
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(401);
            try {
                response.setContentType("text/html;charset=UTF-8");
                response.getWriter().println("没有提供合法的令牌,访问被拒绝~");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
